package com.smart.common.scheduler.service;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.net.URLDecoder;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.smart.common.enums.SmsTemplateEnum;
import com.smart.mapper.HotWorkMapper;
import com.smart.mapper.ProjectMapper;
import com.smart.model.domain.HotWorkDO;
import com.smart.model.domain.ProjectDO;
import com.smart.service.ProjectUseControlService;
import com.smart.utils.SmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.List;

/**
 * @author: zyh
 * @date: 2023-09-25
 */
@Slf4j
@Component
public class HotWorkScheduleService {
    @Value("${aliyun-oss.end-point}")
    private String endPoint;
    @Value("${aliyun-oss.access-key}")
    private String accessKey;
    @Value("${aliyun-oss.secret-key}")
    private String secretKey;
    @Value("${aliyun-oss.bucket-name}")
    private String bucketName;

    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private HotWorkMapper hotWorkMapper;
    @Autowired
    private ProjectUseControlService projectUseControlService;

    public void hotWorkHaveNotUploaded() {
        LocalDate localDate = LocalDate.now();
        //周一
        LocalDate monday = localDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        //周五
        LocalDate friday = localDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.FRIDAY));
        Date startTime = Date.from(monday.atStartOfDay(ZoneId.systemDefault()).toInstant());
        Date endTime = DateUtil.parse(DateUtil.format(Date.from(friday.atStartOfDay(ZoneId.systemDefault()).toInstant()),
                DatePattern.NORM_DATE_PATTERN) + " 23:59:59", DatePattern.NORM_DATETIME_PATTERN);
        List<ProjectDO> projectDOS = projectMapper.selectProjectByStatus();
        projectDOS.stream().filter(item -> projectUseControlService.hotWorkScheduleOpenValid(item.getId()))
                .forEach(item -> {
                    Integer count = hotWorkMapper.selectCountByParams(item.getId(), startTime, endTime);
                    if (count < 1) {
                        String shigongHeadPhone = item.getShigongHeadPhone();
                        String shigongContactPhone = item.getShigongContactPhone();
                        //SmsUtil.sendMessage(shigongContactPhone, SmsTemplateEnum.SMS_463226023);
                        SmsUtil.sendMessage(shigongHeadPhone, SmsTemplateEnum.SMS_463191288);
                    }
                });
    }

    public void hotWorkManagementHaveNotPass() {
        List<ProjectDO> projectDOS = projectMapper.selectProjectByStatus();
        projectDOS.stream().filter(item -> !projectUseControlService.hotWorkManagementScheduleOpenValid(item.getId()))
                .forEach(item -> {
                    String shigongHeadPhone = item.getShigongHeadPhone();
                    String shigongContactPhone = item.getShigongContactPhone();
                    //SmsUtil.sendMessage(shigongContactPhone, SmsTemplateEnum.SMS_463260010);
                    //SmsUtil.sendMessage(shigongHeadPhone, SmsTemplateEnum.SMS_463186268);
                });
    }

    public void deletedHotWorkVideo() {
        List<HotWorkDO> hotWorkDOS = hotWorkMapper.selectDeletedVideo();
        try {
            OSS oss = new OSSClientBuilder().build(endPoint, accessKey, secretKey);
            hotWorkDOS.forEach(item -> {
                String inScene = item.getInScene();
                String startScene = item.getStartScene();
                String endScene = item.getEndScene();
                if (StringUtils.isNotEmpty(inScene)) {
                    String decodedUrl = URLDecoder.decode(inScene, Charset.defaultCharset());
                    if (StringUtils.isNotEmpty(decodedUrl) && decodedUrl.contains(bucketName)) {
                        String[] split = decodedUrl.split(".com/");
                        if (split.length == 2) {
                            boolean exist = oss.doesObjectExist(bucketName, split[1]);
                            if (exist) {
                                oss.deleteObject(bucketName, split[1]);
                            }
                            item.setInScene("");
                        }
                    }
                }
                if (StringUtils.isNotEmpty(startScene)) {
                    String decodedUrl = URLDecoder.decode(startScene, Charset.defaultCharset());
                    if (StringUtils.isNotEmpty(decodedUrl) && decodedUrl.contains(bucketName)) {
                        String[] split = decodedUrl.split(".com/");
                        if (split.length == 2) {
                            boolean exist = oss.doesObjectExist(bucketName, split[1]);
                            if (exist) {
                                oss.deleteObject(bucketName, split[1]);
                            }
                            item.setStartScene("");
                        }
                    }
                }
                if (StringUtils.isNotEmpty(endScene)) {
                    String decodedUrl = URLDecoder.decode(endScene, Charset.defaultCharset());
                    if (StringUtils.isNotEmpty(decodedUrl) && decodedUrl.contains(bucketName)) {
                        String[] split = decodedUrl.split(".com/");
                        if (split.length == 2) {
                            boolean exist = oss.doesObjectExist(bucketName, split[1]);
                            if (exist) {
                                oss.deleteObject(bucketName, split[1]);
                            }
                            item.setEndScene("");
                        }
                    }
                }
                hotWorkMapper.updateDO(item);
            });
            oss.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("动火作业超过三个月视频定时删除->{}", e);
        }
    }
}
